package ferri.lorenzo;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.LinkedList;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

public class recvThread extends Thread {

	public static DatagramSocket socket;
	public static DatagramPacket packet;
	String str = new String("Discovery: Who is out there?\n");
	String[] received = null;
	private Handler handler;
	LinkedList<String> IpAdresses = new LinkedList<String>();
	LinkedList<String> hostName = new LinkedList<String>();
	LinkedList<String> MAC = new LinkedList<String>();
	private static final String TAG = "Discovery";
	private static final int DISCOVERY_PORT = 30303;
	private static final int TIMEOUT_MS = 2000;

	public recvThread(Handler handle) {
		// TODO Auto-generated constructor stub
		this.handler = handle;

	}

	public void run() {
		try {
			socket = new DatagramSocket(DISCOVERY_PORT);
			socket.setBroadcast(true);
			socket.setSoTimeout(TIMEOUT_MS);
			int j = 0;
			sendDiscoveryRequest(socket);
			listenForResponses();
			j=hostName.size();
			Log.d("tag", "" + j);

			received = new String[j];
			for (int i = 0; i < j; i++)
				received[i] = hostName.get(i);

			if (j == 0) {
				received = new String[1];
				received[0] = "nessun dispositivo".toString();
			}

		} catch (IOException e) {
			Log.e(TAG, "Could not send discovery request", e);
		}
		notifyMessage(received);
	}

	private void sendDiscoveryRequest(DatagramSocket socket) throws IOException {

		InetAddress address = InetAddress.getByName("255.255.255.255");
		packet = new DatagramPacket(str.getBytes(), str.length(), address,
				DISCOVERY_PORT);
		socket.send(packet);
	}

	/**
	 * Listen on socket for responses, timing out after TIMEOUT_MS
	 * 
	 **/
	private void listenForResponses()
			throws IOException {
		byte[] buf = new byte[1024];
		String rec = new String();
		try {
			int i = 0;

			while (true) {

				packet = new DatagramPacket(buf, buf.length);
				socket.receive(packet);
				String s = new String(packet.getData(), 0, packet.getLength());
				if (i > 0) {
					String[] split = s.split("\n");
					rec = split[0].toString();
					String ip = packet.getAddress().toString().replace("/", "");

					if (split.length > 1)
						SetMacAddress(split[1]);

					SetipAddress(ip);
					SetHostName(rec);

				}

				Log.d(TAG, "Received response " + s);
				i++;
			}
		} catch (Exception e) {
			Log.d(TAG, "Error");
		}
		finally{
			socket.close();
		}
	
		
	}

	
	private void SetMacAddress(String string) {
		// TODO Auto-generated method stub
		MAC.add(string);
	}

	private void SetipAddress(String ip) {
		// TODO Auto-generated method stub
		IpAdresses.add(ip);

	}

	private void SetHostName(String name) {
		// TODO Auto-generated method stub
		hostName.add(name);

	}

	public String getIpAddress(int position) {

		return IpAdresses.get(position);
	}

	public int getNumIp() {
		return IpAdresses.size();

	}

	public String getMAC(int position) {
		return MAC.get(position);

	}

	public String getHostName(int position) {

		return hostName.get(position);

	}

	private void notifyMessage(String[] str) {
		Message msg = handler.obtainMessage();
		Bundle b = new Bundle();
		b.putStringArray("refresh", str);
		msg.setData(b);
		handler.sendMessage(msg);
	}

}
